package com.mavenq.fly.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * 签名⽅法类
 */
public class TokenUtils {
    private static final Logger logger = LoggerFactory.getLogger(TokenUtils.class);
    private static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8",
            "9", "a", "b", "c", "d", "e",
            "f"};

    public static String getSignature(String pwd, String paramUrl) {
        if (StringUtils.isNotBlank(paramUrl)) {
            try {
                paramUrl = URLDecoder.decode(paramUrl, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("⽣成signData失败:", e);
                throw new RuntimeException("⽣成signData失败:", e);
            }
        }
        String[] paraArray = new String[]{};
        if (StringUtils.isNotBlank(paramUrl)) {
            String[] queryArray = paramUrl.split("&");
            paraArray = (String[]) ArrayUtils.addAll(queryArray, paraArray);
        }
        Arrays.sort(paraArray);
        StringBuffer buffer = new StringBuffer();
        buffer.append(pwd);
        buffer.append(":");
        for (int i = 0; i < paraArray.length; i++) {
            buffer.append(paraArray[i]);
            buffer.append("&");
        }
        buffer.deleteCharAt(buffer.length() - 1);
        buffer.append(":");
        buffer.append(pwd);
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-256");
            md.update(buffer.toString().getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            logger.error("⽣成signData失败:", e);
            throw new RuntimeException("⽣成signData失败.", e);
        } catch (UnsupportedEncodingException e) {
            logger.error("⽣成signData失败:", e);
            throw new RuntimeException("⽣成signData失败.", e);
        }
        String encode = byteArrayToHexString(md.digest());
        return encode;
    }

    private static String byteArrayToHexString(byte[] byteArray) {
        StringBuffer sb = new StringBuffer();
        for (byte byt : byteArray) {
            sb.append(byteToHexString(byt));
        }
        return sb.toString();
    }

    private static String byteToHexString(byte byt) {
        int n = byt;
        if (n < 0)
            n = 256 + n;
        return hexDigits[n / 16] + hexDigits[n % 16];
    }
}